package util;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.representation.Form;
import dto.OrderNotifyDto;

import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by CHENCO7 on 7/28/2017.
 */
public class HttpUtil {
    public static void sendRequest(String url, Object o) {
        Client client = Client.create();
        Form form = new Form();
        form.add("orderNotifyDto", JsonUtil.toJsonString(o));
        WebResource wr = client.resource(url);
        String response =wr.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(String.class, JsonUtil.toJsonString(o));
        System.out.println(response);
    }

    public static String getResponseStr(String uri) throws Exception {
        byte[] buf = null;
        InputStream in = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(uri);
            URLConnection connection = url.openConnection();
            httpURLConnection = (HttpURLConnection) connection;
            httpURLConnection.setRequestMethod("GET");

            in = httpURLConnection.getInputStream();
            int len = in.available();
            buf = new byte[len];
            in.read(buf);
        } catch (IOException e) {
            throw new Exception(e);
        } finally {
            try {
                in.close();
                httpURLConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new String(buf, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
//        String i = HttpUtil.getResponseStr("http://ZHA-ITA077-w7:8080/admins/c/all");
//        System.out.println(i);
//    	List<MerchantDto> t = (List<MerchantDto>) JsonUtil.toJsonObject(i, List.class);
//    	System.out.println(t.size());
        OrderNotifyDto dto = new OrderNotifyDto("11236","7777778");
        HttpUtil.sendRequest("http://10.222.29.154:8080/client/sendToMerchants2", dto);
    }
}
